package com.fast.framework.config.security.jwt;

import cn.hutool.core.util.ObjUtil;
import com.fast.framework.core.domain.User;
import com.fast.framework.enums.JwtEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * jwt 登录授权过滤器。引用的位置：SecurityConfig文件里的 `configure(HttpSecurity http)-> http.addFilterBefore`
 * 注意：创建导入`@Autowired`爆红的原因是因为没有在 SecurityConfig文件中声明托管这个Bean
 * </p>
 *
 * @author lanyuankeji
 */
@Component
public class JwtTAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final String tokenHeader = JwtEnum.tokenHeader.getValue();

    private static final String tokenHead = JwtEnum.tokenHead.getValue();

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 过滤器的内部处理逻辑
     *
     * @param request     HTTP 请求对象
     * @param response    HTTP 响应对象
     * @param filterChain 过滤器链
     * @throws ServletException Servlet 异常
     * @throws IOException      IO 异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      /*  // 获取请求携带的令牌
        String token = request.getHeader(tokenHeader);

        // 不存在 token
        if (null != token && token.startsWith(tokenHead)) {
            if (!StringUtils.hasText(token.substring(tokenHead.length()))) {
                throw new AccessDeniedException("用户未登录！！！");
            }

            // 存在 token
            token = token.substring(tokenHead.length());
*/
        User loginUser = jwtTokenUtil.getLoginUser(request);

        if (ObjUtil.isNotNull(loginUser) && ObjUtil.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            //验证令牌
            jwtTokenUtil.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
//        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }

}
